package cn.broadsense.web.controller.biz;

import cn.broadsense.biz.bo.channel.ChannelOrgBo;
import cn.broadsense.biz.bo.channel.ChannelTagBo;
import cn.broadsense.biz.domain.Channel;
import cn.broadsense.biz.domain.ChannelOrg;
import cn.broadsense.biz.dto.ChannelOrgTreeDto;
import cn.broadsense.biz.service.ChannelOrgService;
import cn.broadsense.biz.service.ChannelService;
import cn.broadsense.biz.vo.ChannelVo;
import cn.broadsense.biz.vo.SearchChannelVo;
import cn.broadsense.common.core.controller.BaseController;
import cn.broadsense.common.core.domain.R;
import cn.broadsense.common.core.page.TableDataInfoResult;
import cn.broadsense.common.utils.poi.ExcelUtil;
import cn.broadsense.system.service.ISysConfigService;
import cn.broadsense.thrid.api.DaHuaApiRepository;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 点位数据
 *
 * @author: pengxin
 * @create: 2023-09-12 11:19
 * @Version 1.0
 **/
@RestController
@Api(tags = "点位数据")
@RequestMapping("/channel")
public class ChannelController extends BaseController {

    @Resource
    private ChannelService channelService;

    @Autowired
    private DaHuaApiRepository daHuaApiRepository;

    @Resource
    private ChannelOrgService channelOrgService;

    @Resource
    private ISysConfigService sysConfigService;


    @PreAuthorize("@ss.hasPermi('biz:channel:list')")
    @GetMapping("/list")
    @ApiOperation("获取点位列表")
    public R<TableDataInfoResult<List<Channel>>> list(Channel channel) {
        List<Channel> list = channelService.findPage(channel);
        return R.ok(getDataTableResult(list));
    }


    @PreAuthorize("@ss.hasPermi('biz:channel:list')")
    @GetMapping("/channelList")
    @ApiOperation("点位管理页面列表")
    public R<TableDataInfoResult<List<Channel>>> channelList(Channel channel) {
        List<Channel> list = channelService.findPageV2(channel);
        return R.ok(getDataTableResult(list));
    }

    @ApiOperation("导出")
    @PostMapping("/export")
    public void export(HttpServletResponse response, Channel channel) {
        List<Channel> list = channelService.getList(channel);
        ExcelUtil<Channel> util = new ExcelUtil<>(Channel.class);
        util.exportExcel(response, list, "设备数据");
    }


    @GetMapping("/search/channelList")
    @ApiOperation("区域搜索点位列表")
    public R<TableDataInfoResult<List<Channel>>> searchChannelList(@Validated SearchChannelVo searchChannelVo) {
        startPage();
        List<Channel> list = channelService.searchChannelList(searchChannelVo);
        return R.ok(getDataTableResult(list));
    }


    //    @PreAuthorize("@ss.hasPermi('biz:channel:list')")
    @GetMapping("/org/channelList")
    @ApiOperation("获取组织架构下面的点位列表")
    public R<TableDataInfoResult<List<Channel>>> queryOrgchannelList(ChannelOrgBo channel) {
        List<Channel> list = channelService.queryOrgChannels(channel);
        return R.ok(getDataTableResult(list));
    }

    @GetMapping("/tag/channelList")
    @ApiOperation("获取标签下面的点位列表")
    public R<TableDataInfoResult<List<Channel>>> queryTagchannelList(ChannelTagBo channel) {
        List<Channel> list = channelService.queryTagChannels(channel);
        return R.ok(getDataTableResult(list));
    }


    @PreAuthorize("@ss.hasPermi('biz:channel:list')")
    @GetMapping("/channelOrg/list/{parentCode}")
    @ApiOperation("获取点位组织列表")
    public R<List<ChannelOrg>> list(@ApiParam(value = "父类编码第一次填0", example = "0") @PathVariable String parentCode) {
        List<ChannelOrg> channelOrgList = channelService.channelOrgByParentCode(parentCode);
        return R.ok(channelOrgList);
    }

    @PreAuthorize("@ss.hasPermi('biz:channel:list')")
    @GetMapping("/channelOrg/treeList")
    @ApiOperation("获取点位组织树列表")
    public R<List<ChannelOrgTreeDto>> treeList(@RequestParam(required = false, defaultValue = "8846662830000320") String orgCode) {

        String treeOrgCode = sysConfigService.selectConfigByKey("tree_org_code");
        if (StrUtil.isNotBlank(treeOrgCode)) {
            orgCode = treeOrgCode;
        }

        List<ChannelOrgTreeDto> channelOrgList = channelOrgService.orgTree(orgCode);
        return R.ok(channelOrgList);
    }


    @PreAuthorize("@ss.hasPermi('biz:channel:details')")
    @GetMapping("/{id}")
    @ApiOperation("获取点位详情")
    public R<Channel> details(@PathVariable Long id) {
        Channel details = channelService.getDetails(id);
        return R.ok(details);
    }


    @PreAuthorize("@ss.hasPermi('biz:channel:details')")
    @GetMapping("/playChannel/{id}")
    @ApiOperation("点位视频播放")
    public R playChannel(@PathVariable Long id) {
        Channel channel = channelService.getById(id);
        JSONObject play = daHuaApiRepository.play(channel.getChannelCode());
        if (play != null && play.containsKey("url")) {
            String url = play.getString("url");
            play.put("url", replacePlayUrl(url));
        }
        return R.ok(play);
    }

    /**
     * 替换播放URL
     *
     * @param url
     * @return
     */
    private String replacePlayUrl(String url) {
        if (url != null) {
            url = url.replace("http://10.1.0.40:8050/cam/", "http://172.29.28.190/cam/");
            url = url.replace("http://10.1.0.41:8050/cam/", "http://172.29.28.190/cam1/");
            url = url.replace("http://10.1.0.42:8050/cam/", "http://172.29.28.190/cam2/");
            url = url.replace("http://10.1.0.43:8050/cam/", "http://172.29.28.190/cam3/");
            url = url.replace("http://10.1.0.44:8050/cam/", "http://172.29.28.190/cam4/");
        }
        return url;
    }

    @PreAuthorize("@ss.hasPermi('biz:channel:details')")
    @PostMapping("/follow/{id}/{type}")
    @ApiOperation("点位收藏")
    public R followChannel(@ApiParam(value = "点位id") @PathVariable Long id, @ApiParam(value = "操作类型 1=收藏 2=取消收藏", example = "0") @PathVariable Integer type) {
        channelService.followChannel(id, type);
        return R.ok();
    }


    @PutMapping("/{id}")
    @PreAuthorize("@ss.hasPermi('biz:channel:edit')")
    @ApiOperation("点位编辑")
    public R editChannel(@ApiParam(value = "点位id") @PathVariable Long id, @RequestBody ChannelVo channelVo) {
        channelService.edit(id, channelVo);
        return R.ok();
    }


    @ApiOperation("添加自定义点位标签")
    @PostMapping("/{channelId}/customTag")
    public R<Void> addCustomTag(@ApiParam(value = "点位id") @PathVariable Long channelId, @ApiParam(value = "自定义标签名称") @RequestParam String customTag) {
        channelService.addCustomTag(channelId, customTag);
        return R.ok();
    }

    @ApiOperation("修改自定义点位标签")
    @PutMapping("/customTag/{id}")
    public R<Void> editCustomTag(@ApiParam(value = "自定义标签id") @PathVariable Long id, @ApiParam(value = "自定义标签名称") @RequestParam String customTag) {
        channelService.editCustomTag(id, customTag);
        return R.ok();
    }

    @ApiOperation("删除自定义点位标签")
    @DeleteMapping("/customTag/{id}")
    public R<Void> delCustomTag(@ApiParam(value = "自定义标签id") @PathVariable Long id) {
        channelService.delCustomTag(id);
        return R.ok();
    }


    @PostMapping("/import")
    @ApiOperation("导入点位")
    public R importData(MultipartFile file) throws Exception {
        ExcelUtil<ChannelVo> util = new ExcelUtil<ChannelVo>(ChannelVo.class);
        List<ChannelVo> list = util.importExcel(file.getInputStream());
        channelService.importData(list);
        return R.ok();
    }

    @ApiOperation("导入模板下载")
    @GetMapping("/importIotTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<ChannelVo> util = new ExcelUtil<ChannelVo>(ChannelVo.class);
        util.importTemplateExcel(response, "导入模板数据");
    }

}
